package com.jzy.gitee4mweb.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.util.StrUtil;

@RestController
@RequestMapping(value = "/gitee")
public class GiteePic {
    @Value("${Gitee.URL}")
    private String url;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<Map<String, Object>> upload(HttpServletRequest request) {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
        String access_token = params.getParameter("access_token");
        String owner = params.getParameter("owner");
        String repo = params.getParameter("repo");
        String path = params.getParameter("path");
        if (StrUtil.isEmpty(access_token)) {
            rtnMap = setRtnMap("fail", "参数access_token缺失", null);
            return new ResponseEntity<Map<String, Object>>(rtnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (StrUtil.isEmpty(owner)) {
            rtnMap = setRtnMap("fail", "参数owner缺失", null);
            return new ResponseEntity<Map<String, Object>>(rtnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (StrUtil.isEmpty(repo)) {
            rtnMap = setRtnMap("fail", "参数repo缺失", null);
            return new ResponseEntity<Map<String, Object>>(rtnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (StrUtil.isEmpty(path)) {
            rtnMap = setRtnMap("fail", "参数path缺失", null);
            return new ResponseEntity<Map<String, Object>>(rtnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        String today = DateUtil.format(new Date(), "yyyyMMdd");
        JSONObject resultObject = new JSONObject();
        if (!file.isEmpty()) {
            try {
                path = path + "/" + today.substring(0, 4) + "/" + today.substring(4, 6)
                        + "/" + today.substring(6, 8) + "/"
                        + IdUtil.simpleUUID()
                        + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                byte[] bytes = file.getBytes();
                String base64Str = Base64.getEncoder().encodeToString(bytes);
                String result = postImg(access_token, owner, repo, path, base64Str);
                resultObject = JSONUtil.parseObj(result);
            } catch (IOException e) {
                rtnMap = setRtnMap("fail", "上传失败", null);
                return new ResponseEntity<Map<String, Object>>(rtnMap, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        if (resultObject.getJSONObject("commit") == null) {
            rtnMap = setRtnMap("fail", resultObject.getStr("message"), null);
            return new ResponseEntity<Map<String, Object>>(rtnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        rtnMap = setRtnMap("success", "上传成功", resultObject.getJSONObject("content").getStr("download_url"));
        return new ResponseEntity<Map<String, Object>>(rtnMap, HttpStatus.OK);
    }

    public String postImg(String access_token, String owner, String repo, String path, String base64Str) {
        String postUrl = url + owner + "/" + repo + "/contents/" + path;
        JSONObject jsonBody = JSONUtil.createObj()
                .set("access_token", access_token)
                .set("owner", owner)
                .set("repo", repo)
                .set("path", path)
                .set("content", base64Str)
                .set("message", "Gitee4MWeb push");
        String jsonMsg = jsonBody.toString();
        String result = HttpRequest.post(postUrl).body(jsonMsg).execute().body();
        return result;
    }

    public Map<String, Object> setRtnMap(String status, String info, String url) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("info", info);
        map.put("url", url);
        return map;
    }
}
